package com.atguigu.gulimall.product.exception;

import com.atguigu.common.utils.R;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.atguigu.common.exception.BizCodeEnum.UNKNOW_EXCEPTION;
import static com.atguigu.common.exception.BizCodeEnum.VALID_EXCEPTION;

@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class ControllerExcHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R doException(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String,String> map = new HashMap<>();
        fieldErrors.forEach((error)->{
            String field = error.getField();
            String message = error.getDefaultMessage();
            map.put(field,message);
        });
        return R.error(VALID_EXCEPTION.getCode(), VALID_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(Exception.class)
    public R doOtherException(Exception e){
        return R.error(UNKNOW_EXCEPTION.getCode(), UNKNOW_EXCEPTION.getMsg()).put("data",e.getMessage());
    }
}
